import os
import requests
from pathlib import Path
import time
import json
from config import *  # 导入所有配置

def verify_api_connection():
    """验证API连接是否正常"""
    try:
        url = f"{COMPREFACE_BASE_URL}/api/v1/recognition/subjects"
        headers = {
            'x-api-key': RECOGNITION_API_KEY
        }
        
        print(f"尝试连接: {url}")
        response = requests.get(url, headers=headers, timeout=TIMEOUT)
        
        print(f"API响应状态码: {response.status_code}")
        if response.status_code == 200:
            print("✓ API连接正常")
            print(f"响应内容: {response.text[:200]}...")
            return True
        else:
            print(f"✗ API连接异常，状态码: {response.status_code}")
            print(f"响应内容: {response.text}")
            return False
    except requests.exceptions.RequestException as e:
        print(f"✗ API连接失败: {str(e)}")
        return False

def create_subject(subject_name):
    """创建主题（如果不存在）"""
    url = f"{COMPREFACE_BASE_URL}/api/v1/recognition/subjects"
    headers = {
        'Content-Type': 'application/json',
        'x-api-key': RECOGNITION_API_KEY
    }
    data = {
        "subject": subject_name
    }
    
    try:
        print(f"创建主题: {subject_name}")
        response = requests.post(url, headers=headers, json=data, timeout=TIMEOUT)
        
        if response.status_code in [200, 201]:
            print(f"✓ 主题创建成功: {subject_name}")
            return True
        else:
            print(f"✗ 主题创建失败: {subject_name}, 状态码: {response.status_code}")
            print(f"错误信息: {response.text}")
            return False
    except Exception as e:
        print(f"创建主题时发生错误: {str(e)}")
        return False

def upload_image(image_path, subject, retry=0):
    """上传单个图片到CompreFace"""
    # 先创建主题
    create_subject(subject)
    
    # 使用查询参数指定subject
    url = f"{COMPREFACE_BASE_URL}/api/v1/recognition/faces?subject={subject}"
    headers = {
        'x-api-key': RECOGNITION_API_KEY
    }
    
    with open(image_path, 'rb') as img_file:
        # 使用form表单上传文件
        files = {'file': img_file}
        
        print(f"正在上传: {image_path} (标签: {subject})")
        print(f"请求URL: {url}")
        try:
            response = requests.post(
                url,
                headers=headers,
                files=files,
                timeout=TIMEOUT
            )
            
            print(f"响应状态码: {response.status_code}")
            if response.status_code == 200:
                print(f"✓ 上传成功: {image_path}")
                print(f"响应内容: {response.text[:100]}...")
                return True
            else:
                print(f"✗ 上传失败: {image_path}, 状态码: {response.status_code}")
                print(f"错误信息: {response.text}")
                return False
                
        except requests.exceptions.Timeout:
            print(f"请求超时: {image_path}")
            if retry < MAX_RETRIES:
                print(f"尝试重试 ({retry+1}/{MAX_RETRIES})...")
                time.sleep(2)  # 等待2秒后重试
                return upload_image(image_path, subject, retry+1)
            return False
            
        except requests.exceptions.ConnectionError as e:
            print(f"连接错误: {str(e)}")
            print("请检查CompreFace服务是否正在运行，以及API地址是否正确")
            if retry < MAX_RETRIES:
                print(f"尝试重试 ({retry+1}/{MAX_RETRIES})...")
                time.sleep(2)  # 等待2秒后重试
                return upload_image(image_path, subject, retry+1)
            return False
            
        except Exception as e:
            print(f"发生错误: {str(e)}")
            return False

def is_image_file(file_path):
    """检查文件是否为支持的图片格式"""
    return Path(file_path).suffix.lower() in IMAGE_EXTENSIONS

def process_directory(directory_path):
    """处理指定目录中的内容"""
    base_dir = Path(directory_path)
    
    # 遍历目录中的所有项目
    for item in base_dir.iterdir():
        # 跳过apikey.txt文件
        if item.name == "apikey.txt":
            continue
        
        # 如果是目录，以目录名作为subject上传其中的图片
        if item.is_dir():
            subject = item.name
            print(f"\n处理文件夹: {subject}")
            
            # 遍历文件夹中的所有文件
            for img_file in item.iterdir():
                if is_image_file(img_file):
                    upload_image(str(img_file), subject)
        
        # 如果是图片文件，以文件名作为subject上传
        elif is_image_file(item):
            # 使用不带扩展名的文件名作为subject
            subject = item.stem
            upload_image(str(item), subject)

def main():
    """主函数"""
    try:
        print(f"使用人脸识别API密钥: {RECOGNITION_API_KEY[:8]}...{RECOGNITION_API_KEY[-8:]}")
        
        # 验证API连接
        print("正在验证API连接...")
        if not verify_api_connection():
            print("API连接验证失败，请检查CompreFace服务是否正在运行")
            print(f"当前API地址: {COMPREFACE_BASE_URL}")
            return
            
        # 处理上传目录
        print(f"开始处理目录: {UPLOAD_DIR}")
        process_directory(UPLOAD_DIR)
        
        print("\n所有上传任务完成!")
    except Exception as e:
        print(f"发生错误: {str(e)}")
        print(f"错误类型: {type(e).__name__}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main() 